package nl.hanze.designpatterns.DAO.impl.file.crypted;

import nl.hanze.designpatterns.DAO.LoginCredentialDAO;
import nl.hanze.designpatterns.DAO.impl.file.BaseFDAOImpl;
import nl.hanze.designpatterns.Domain.LoginCredential;
import nl.hanze.designpatterns.io.CryptedInputStream;
import nl.hanze.designpatterns.io.CryptedOutputStream;

import java.io.*;
import java.util.ArrayList;
import java.util.List;

/**
 * Created by Aron on 6-10-2014.
 */
public class LoginCredentialFDAOImpl extends BaseFDAOImpl implements LoginCredentialDAO {

    private static final String path = new File("src/main/java/nl/hanze/designpatterns/files").getAbsolutePath().concat("/LoginCredentialsFile.file");

    @Override
    public boolean isValid(LoginCredential logincredential) {
        System.out.println("<BaseFDAOImpl>[isValid]logincredential "+logincredential);
        ArrayList<LoginCredential> list = Deserialize();
        for (LoginCredential credential : list) {
            System.out.println("credential "+credential);
            if (logincredential.equals(credential)) {
                return true;
            }
        }
        return false;
    }


    public static void Serialize(ArrayList<LoginCredential> credentials) {
        try
        {
            FileOutputStream fileOut = new FileOutputStream(path);
            CryptedOutputStream cryptOut = new CryptedOutputStream(fileOut);
            ObjectOutputStream out = new ObjectOutputStream(cryptOut);
            out.writeObject(credentials);
            out.close();
            fileOut.close();
        }catch(IOException i)
        {
            i.printStackTrace();
        }
    }

    public static ArrayList<LoginCredential> Deserialize() {
        ArrayList<LoginCredential> credentials = null;
        try
        {
            FileInputStream fileIn = new FileInputStream(path);
            CryptedInputStream cryptIn = new CryptedInputStream(fileIn);
            ObjectInputStream in = new ObjectInputStream(cryptIn);
            credentials = (ArrayList<LoginCredential>) in.readObject();
            in.close();
            fileIn.close();
            return credentials;
        }catch(IOException i)
        {
            i.printStackTrace();
            return null;
        }catch(ClassNotFoundException c)
        {
            c.printStackTrace();
            return null;
        }
    }
}
